import React, { useEffect, useState } from 'react';
import { NavBar } from 'antd-mobile';
import styles from './index.module.css';
import { Search, Toast, Dialog } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import { debounce } from 'lodash';
import http from '../../utils/http';
import { DeleteO } from '@react-vant/icons';

const Index: React.FC = () => {
    const [visible, setVisible] = useState(false)
    const navigate = useNavigate();
    const [value, setValue] = useState('');
    const [searchList, setSearchList] = useState<any[]>([]);  // 强化类型，存储搜索结果
    const [history, setHistory] = useState<string[]>([]);  // 存储历史搜索记录

    // 获取历史搜索记录
    useEffect(() => {
        const savedHistory = localStorage.getItem('searchHistory');
        if (savedHistory) {
            setHistory(JSON.parse(savedHistory));
        }
    }, []);

    // 发起请求获取搜索结果
    const getlist = (searchValue: string) => {
        if (!searchValue.trim()) {
            setSearchList({ doctor: [], book: [], soco: [] });  // 如果搜索值为空，清空结果
            return;
        }
        http.get('/search', { params: { searchValue } }).then((result) => {
            const { code, data } = result.data;
            if (code === 20000) {
                setSearchList(data);  // 更新搜索结果
            } else {
                Toast.fail('搜索失败，请稍后再试');  // 如果请求失败，提示用户
            }
        })
    };

    // 跳医生详情页
    const toDetail = (item: any) => {
        navigate(`/doctor/` + item.id, { state: item })
    }
    // 使用lodash的debounce来延迟搜索操作
    const debouncedSearch = debounce((value: string) => {
        getlist(value);
    }, 500);

    // 处理输入框变化
    const handleSearchChange = (value: string) => {
        setValue(value);
        debouncedSearch(value);  // 在输入时触发debouncedSearch
    };

    // 手动触发搜索
    const handleSearch = () => {
        if (value.trim() && !history.includes(value.trim())) {
            const newHistory = [value.trim(), ...history];  // 新搜索词放在最前面
            setHistory(newHistory);
            localStorage.setItem('searchHistory', JSON.stringify(newHistory));  // 保存到localStorage
        }
        getlist(value);
    };

    // 删除历史记录
    const handleDeleteHistory = (keyword: string) => {
        Dialog.confirm({
            title: '提示',
            message: '确定清空搜索记录？',
            onCancel: () => console.log('cancel'),
            onConfirm: () => {
                const newHistory = history.filter((item) => item !== keyword);
                setHistory(newHistory);
                localStorage.setItem('searchHistory', JSON.stringify(newHistory));
                setVisible(false);
            },
        })
    };

    // 返回上一页
    const back = () => {
        navigate(-1);
    };

    // 初始加载时，如果有默认值，进行一次搜索
    useEffect(() => {
        if (value.trim()) {
            getlist(value);
        }
    }, []);
    console.log(searchList)
    return (
        <div className={styles.search_box}>
            {/* 返回按钮 */}
            <div className={styles.searchtwo}>
                <NavBar onBack={back}>搜索</NavBar>
            </div>

            {/* 搜索框 */}
            <div className={styles.search_one}>
                <Search
                    showAction
                    value={value}
                    onChange={handleSearchChange}  // 监听搜索框变化
                    onSearch={handleSearch}  // 监听按下搜索时触发
                    actionText={<div onClick={handleSearch}>搜索</div>}
                    placeholder="请输入搜索关键词"
                />
            </div>

            {/* 搜索结果 */}
            <div className={styles.search_list}>
                {searchList?.doctor?.length > 0 ? (
                    searchList.doctor.map((item, index) => (
                        <div key={index} className={styles.doctor} onClick={()=>toDetail(item)}>
                            <div className={styles.doctor_information}>
                                <div className={styles.avatar}>
                                    <img src={item.doctorimage} alt="" style={{ width: '80px', height: '80px' }} />
                                </div>
                            </div>
                            <div className={styles.doctor_name}>
                                <p>
                                    <li className={styles.name}>{item.doctorname}</li>
                                    <li className={styles.post}>{item.doctorstate}</li>
                                </p>
                                <p>
                                    <li className={styles.hospital}>{item.doctorcity}</li>
                                    <li className={styles.ke}>{item.doctoradministre}</li>
                                </p>
                                <div className={styles.type}>
                                    <li className={styles.photo}>图文咨询</li>
                                    <li className={styles.phone}>电话咨询</li>
                                    <li className={styles.video}>视频咨询</li>
                                </div>
                                {/* 擅长 */}
                                <div className={styles.good}>
                                    擅长：{item.doctordescword}
                                </div>
                                <div className={styles.assessment}>
                                    <li>
                                        好评率 <span className={styles.color}>{item.doctorgood}%</span>
                                    </li>
                                    <li>
                                        锦旗 <span className={styles.color}>{item.doctorflag}</span>
                                    </li>
                                    <li>
                                        浏览人次 <span className={styles.color}>{item.doctorbrowse}</span>
                                    </li>
                                </div>
                                {/* 价格 */}
                                <div className={styles.about_price}>
                                    <div className={styles.price}>
                                        <div className={styles.price_num}>
                                            <li className={styles.q}>￥</li>
                                            <li className={styles.num}>{item.doctorprice}</li>
                                            <li className={styles.qi}>起</li>
                                        </div>
                                        <button>问医生</button>
                                    </div>
                                </div>
                            </div>
                        </div>  // 根据返回的搜索结果渲染
                    ))
                ) : (
                    <div style={{ display: 'flex' }}>
                        {/* 显示历史记录 */}
                        {history.length > 0 ? (
                            <div className={styles.history_section}>
                                <div className={styles.history_title}>最近搜索</div>
                                {history.map((keyword, index) => (
                                    <div key={index} className={styles.history_item}>
                                        <span className={styles.history_keyword}>{keyword}</span>
                                        <DeleteO
                                            className={styles.history_delete_icon}
                                            fontSize={20}
                                            onClick={() => handleDeleteHistory(keyword)}
                                        />
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className={styles.history_section}>
                                <div className={styles.history_title}>最近搜索</div>
                                <div style={{ marginLeft: '20px', marginTop: '20px' }}>暂无历史记录</div>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};

export default Index;
